import * as turf from '@turf/turf'
import { default as proj4 } from 'proj4'
function useProjectionHelper() {
    function convertPolygon(
        epsgSource: string,
        // epsgTarget: string,
        polygonCoordinates: number[][],
    ) {

        const sourceCode = matchSrsCode(epsgSource)

        if(sourceCode){
            proj4.defs(sourceCode,epsgSource)

            const transformer = proj4(sourceCode, 'EPSG:4326').forward

            const convertedPolygon = polygonCoordinates.map((coord) => {
                return transformer(coord)
            })

            return convertedPolygon
        }

        
    }

    function matchSrsCode(projString: string) {
        const match = projString.match(/AUTHORITY\["EPSG","(\d+)"\]/g)

        const numberRegex = /(\d+)/g

        console.log('match', match)

        if (match && match.length >= 2) {

            const lastMatch = match[match.length - 1]

            const numberMatch = lastMatch.match(numberRegex)

            if(numberMatch&&numberMatch.length>0){
                const epsgCode = numberMatch[numberMatch.length-1]
                return `EPSG:${epsgCode}`
            }
        } else {
            console.log('EPSG code not found in the string.')
        }
    }

    return {
        convertPolygon,
        matchSrsCode,
    }
}

export default useProjectionHelper
